#!/bin/bash

# 脚本中断时退出
set -e

TARGET=${1:-gitee}

# 删除并重建 dist 目录
if [ -d "dist" ]; then
  rm -rf dist
fi

echo "📦 构建中..."
npm run build

# 进入 dist 目录
cd dist

# 初始化 git 仓库
git init -b main
git add .
git commit -m "deploy: build to $TARGET"

# 根据目标选择远程地址和分支
if [ "$TARGET" = "github" ]; then
  REMOTE_URL="https://github.com/he5050/pro-admin-demo.git"
  BRANCH="gh-pages"
else
  REMOTE_URL="https://gitee.com/he5050/pro-admin-demo.git"
  BRANCH="main"
fi

# 添加远程仓库地址（若未添加则添加）
if ! git remote | grep -q origin; then
  git remote add origin "$REMOTE_URL"
fi

# 清空远程仓库中的目标分支
git push origin --delete "$BRANCH" || true

# 强制推送清空远程内容（全量覆盖）
git push -f origin "$BRANCH"

# 返回原目录
cd -

echo "✅ 部署完成：已将 dist 内容推送到 $TARGET 仓库"